package com.btl.component.web.util;

import com.btl.boot.core.util.ClassUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;

import java.util.Objects;
import java.util.Optional;

/**
 * Web工具
 */
@Slf4j
@UtilityClass
public class WebUtils extends org.springframework.web.util.WebUtils {

    /**
     * 判断是否ajax请求 spring ajax 返回含有 ResponseBody 或者 RestController注解
     *
     * @param handlerMethod HandlerMethod
     * @return 是否ajax请求
     */
    public boolean isBody(HandlerMethod handlerMethod) {
        ResponseBody responseBody = ClassUtils.getAnnotation(handlerMethod, ResponseBody.class);
        return responseBody != null;
    }

    /**
     * 读取cookie
     *
     * @param name cookie name
     * @return cookie value
     */
    public String getCookieVal(String name) {
        if (WebUtils.getRequest()
                .isPresent()) {
            return getCookieVal(WebUtils.getRequest()
                    .get(), name);
        }
        return null;
    }

    /**
     * 读取cookie
     *
     * @param request HttpServletRequest
     * @param name    cookie name
     * @return cookie value
     */
    public String getCookieVal(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie != null ? cookie.getValue() : null;
    }

    /**
     * 清除 某个指定的cookie
     *
     * @param response HttpServletResponse
     * @param key      cookie key
     */
    public void removeCookie(HttpServletResponse response, String key) {
        setCookie(response, key, null, 0);
    }

    /**
     * 设置cookie
     *
     * @param response        HttpServletResponse
     * @param name            cookie name
     * @param value           cookie value
     * @param maxAgeInSeconds maxage
     */
    public void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return {HttpServletRequest}
     */
    public Optional<HttpServletRequest> getRequest() {
        return Optional
                .of(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest());
    }

    /**
     * 获取 HttpServletResponse
     *
     * @return {HttpServletResponse}
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    /**
     * 获取客户端IP
     *
     * @return {String}
     */
    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多个 IP 的情况（通常第一个才是真实来源）
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 获取客户端IP
     *
     * @return {String}
     */
    public String getIp() {
        HttpServletRequest request = getRequest().orElse(null);
        assert request != null;
        return getIp(request);
    }

    /**
     * 获取客户端浏览器
     */
    public String getBrowser() {
        HttpServletRequest httpServletRequest = getRequest().orElse(null);
        return getBrowser(Objects.requireNonNull(httpServletRequest));
    }

    /**
     * 获取客户端浏览器
     */
    public String getBrowser(HttpServletRequest request) {
        //        UserAgentAnalyzer analyzer = UserAgentAnalyzer
//                .newBuilder()
//                .hideMatcherLoadStats()
//                .withCache(10000)
//                .build();
//        UserAgent agent = analyzer.parse(browser);
//        System.out.println("Browser: " + agent.getValue(UserAgent.AGENT_NAME));
//        System.out.println("Browser Version: " + agent.getValue("AgentVersion"));
//        System.out.println("OS: " + agent.getValue("OperatingSystemNameVersion"));
//        System.out.println("Device: " + agent.getValue("DeviceName"));
//        System.out.println("Device Class: " + agent.getValue("DeviceClass"));
//        System.out.println("Is Mobile: " + agent.getValue("IsMobile"));
//        System.out.println("Is Robot: " + agent.getValue("IsRobot"));
        return request.getHeader("User-Agent");
    }

}
